package com.smartcommunity.controller.common;

import com.smartcommunity.entity.image.ImageData;
import com.smartcommunity.lis.BimgClientPool;
import com.smartcommunity.bean.enumeration.ResultCode;
import com.smartcommunity.bean.model.Result;
import com.smartcommunity.controller.BaseController;
import com.smartcommunity.exception.BusinessException;
import com.smartcommunity.lis.BimgException;
import com.smartcommunity.log.interceptor.Log;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liutuan
 * @ClassName: FileConroller
 * @Description: 文件上传操作
 * @date 2018年1月16日 下午5:15:15
 */
@Api(value = "FileConroller", tags = {"文件操作"})
@Slf4j
@RestController
@RequestMapping(value = "/file")
public class FileConroller extends BaseController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private BimgClientPool  lis;
    /**
     * 跳转到上传页面
     * @return
     */
    @RequestMapping(value = "/toUpload")
    @ResponseBody
    public String toUpload() {
        return "upload";
    }


    /**
     * 图片上传到LIS永久保存
     *
     * @param mpFile 图片
     * @return 保存在LIS中的地址
     */
    @ApiOperation(value = "上传文件到LIS,永久保存", notes = "上传文件到LIS,永久保存")
    @PostMapping("/uploadFileToLis")
    @Log(info = "上传文件",module = "资源管理",function = "上传")
    public Result uploadFileToLis(@ApiParam(value = "上传的图片文件", required = true) @RequestParam("mpFile") MultipartFile mpFile) {
        Map<String, String> map = new HashMap<>();
        try {
            String contentType = mpFile.getContentType();
            //文件类型校验
            if (StringUtils.isEmpty(contentType)) {
                return Result.error(ResultCode.MIS_VALID_PARAM);
            }
            byte[] bytes = mpFile.getBytes();
            // 保存到LIS
            String path = lis.uploadImageForever(bytes);
            map.put("path", path);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(ResultCode.SAVE_LIS_ERROR);
        }
        return Result.ok(map);
    }

    @ApiOperation(value = "上传base64图片文件", notes = "上传base64图片文件")
    @PostMapping("/uploadBase64ToLis")
    @Log(info = "上传base64图片文件",module = "资源管理",function = "上传")
    public Result uploadBase64ToLis(@RequestBody ImageData data) {
        String url = null;
        try {
            byte[] bs = Base64.getDecoder().decode(data.getImageData());
            url = lis.uploadImageForever(bs);
        } catch (BimgException e) {
            log.error("上传base64图片文件异常", e);
            return Result.error(ResultCode.SAVE_LIS_ERROR);
        }
        return Result.ok(url);
    }

    /**
     * 文件下载
     */
    @RequestMapping("/downloadFile")
    @ApiOperation(value = "下载模板文件", notes = "下载模板文件", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "模板类型（people:实有人口，camera:监控管理，" +
                    "build:实有楼栋，house:实有房屋，realCompany:实有单位，realCompanyPeople:从业人员,faceLibPerson:人脸库人员信息" +
                    "realPower:实有力量,villageEntranceExit:小区出入口,vehicle:车辆信息,villageOrg:行政区划,sysOrgImport:组织机构,access:门禁设备）", required = true),
    })
    @Log(info = "下载模板文件",module = "资源管理",function = "下载")
    public void downloadFile(@RequestParam(name = "type", required = true) String type) {
        // 设置响应参数
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        FileInputStream fis = null;
        try {
            // 获取jar所在目录
            ApplicationHome applicationHome = new ApplicationHome(getClass());
            String baseDir = applicationHome.getSource().getParentFile().toString() + "/modules/";
            log.info("--------------------------------------------------" + baseDir);
            // 获取模板类型
            String fileName = "";
            if ("people".equals(type)) {
                fileName = baseDir + "实有人口模板.zip";
            } else if ("camera".equals(type)) {
                fileName = baseDir + "监控管理模板.zip";
            } else if ("build".equals(type)) {
                fileName = baseDir + "实有楼栋模板.zip";
            } else if ("realCompany".equals(type)) {
                fileName = baseDir + "实有单位模板.zip";
            } else if ("house".equals(type)) {
                fileName = baseDir + "实有房屋模板.zip";
            } else if ("realVehicleTollgate".equals(type)) {
                fileName = baseDir + "车辆卡口模版.zip";
            } else if ("realEquipmentExit".equals(type)) {
                fileName = baseDir + "实有装备模板.zip";
            } else if ("policeman".equals(type)) {
                fileName = baseDir + "警员模板.zip";
            } else if ("villageEntranceExit".equals(type)) {
                fileName = baseDir + "小区出入口模板.zip";
            } else if ("vehicle".equals(type)) {
                fileName = baseDir + "车辆信息模板.zip";
            } else if ("realPower".equals(type)) {
                fileName = baseDir + "实有力量模板.zip";
            } else if ("villageOrg".equals(type)) {
                fileName = baseDir + "行政区划模板.zip";
            } else if ("sysOrgImport".equals(type)) {
                fileName = baseDir + "组织机构模板.zip";
            } else if ("faceLibPerson".equals(type)) {
                fileName = baseDir + "人脸库人员信息模板.zip";
            } else if ("access".equals(type)) {
                fileName = baseDir + "门禁管理模板.zip";
            } else if ("license".equals(type)) {
                fileName = baseDir + "pbd.key0";
            } else if ("realCompanyPeople".equals(type)) {
                fileName = baseDir + "从业人员模板.zip";
            } else {
                throw new BusinessException("请求的模板类型有误！");
            }
            File file = new File(fileName);
            fis = new FileInputStream(file);
            // UTF-8编码，下载可以正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
        } catch (FileNotFoundException e) {
            throw new BusinessException("指定类型的模板文件未找到！");
        } catch (IOException e) {
            throw new BusinessException("读取文件流失败！");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new BusinessException("关闭输入流失败！");
                }
            }
        }
    }

}
